package com.hyw.trace.configuration.meta.http;

import java.util.Objects;

import org.springframework.http.HttpEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.client.RestTemplate;

import com.hyw.trace.configuration.meta.IEventStorage;
import com.hyw.trace.configuration.meta.TraceEvent;

public class HttpEventStorage implements IEventStorage<TraceEvent> {

  final RestTemplate restTemplate;

  final String uri;

  public HttpEventStorage(@Nullable RestTemplate restTemplate, String uri, boolean debug) {
    super();
    this.uri = uri;
    if (Objects.isNull(restTemplate)) {
      this.restTemplate = new RestTemplate();
    } else {
      this.restTemplate = restTemplate;
    }

    if (debug && this.restTemplate.getInterceptors().stream()
        .noneMatch(p -> p.getClass() == LoggingRequestInterceptor.class)) {
      this.restTemplate.getInterceptors().add(new LoggingRequestInterceptor());
    }

  }

  @Override
  public void storage(TraceEvent data) {
    restTemplate.postForEntity(uri, new HttpEntity<>(data), String.class);
  }

}
